package examlhp.three;

import java.io.*;

public class UserServiceImpl implements UserService{
    @Override
    public boolean register(User user) {
        String name = user.getName();
        File file = new File("D:/" + name + ".txt");
        File file1 = new File("D:/zhangsan.txt");
        FileInputStream fis = null;
        FileOutputStream fos = null;
        if(!file1.exists())
        {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            file.createNewFile();
//            fis = new FileInputStream(file);
            fos = new FileOutputStream(file1);
            String uname = "name=" + user.getName();
            String pwd = "password=" + user.getPassword();
            String username = "username=" + user.getUsername();
            fos.write(uname.getBytes());
            fos.write("\n".getBytes());
            fos.write(username.getBytes());
            fos.write("\n".getBytes());
            fos.write(pwd.getBytes());
            fos.flush();



        } catch (IOException e) {

            throw new RuntimeException(e);
        }finally {
            try {
                fos.close();
//                fis.close();

            } catch (IOException e) {
                throw new RuntimeException(e);

            }

        }
        return true;
    }

    @Override
    public boolean login(String username, String password) {

        File file = new File("D:/张三.txt");
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            String line;
            String uname = "";
            String pwd = "";
            line = br.readLine();
            while((line = br.readLine()) != null)
            {
                uname = line.substring(line.indexOf("=") + 2, line.length());
                line = br.readLine();
                pwd = line.substring(line.indexOf("=") + 2, line.length());
            }

//            System.out.println(uname);
//            System.out.println(pwd);
            if(uname.equals(username) && pwd.equals(password))
            {
                return true;
            }
            else {
                return false;
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        return false;
    }
}
